//
//  WXPKAudioPlayerManager.m
//  WXClassBattle
//
//  Created by tianlong on 2018/5/4.
//  Copyright © 2018年 tianlong. All rights reserved.
//

#import "WXPKAudioPlayerManager.h"
#import "WXPKConfig.h"

@interface WXPKAudioPlayerManager ()<AVAudioPlayerDelegate>
@property (strong, nonatomic) NSMutableDictionary *playerDictM;
@end

@implementation WXPKAudioPlayerManager
- (instancetype)init
{
    self = [super init];
    if (self) {
        // 中断监听
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

        // 线路改变：如插拔耳机
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}

- (NSMutableDictionary *)playerDictM {
    if (!_playerDictM) {
        _playerDictM = [NSMutableDictionary dictionary];
    }
    return _playerDictM;
}

- (WXPKAudioPlayer *)audioPlayerForKey:(NSString *)key {
    id obj = [self.playerDictM objectForKey:key];
    if(obj && [obj isKindOfClass:[WXPKAudioPlayer class]]) {
        return (WXPKAudioPlayer *)obj;
    }
    return nil;
}

#pragma mark - 播放
- (void)playWithFileName:(NSString *)fileName
                fileType:(NSString *)fileType {
    [self playWithFileName:fileName fileType:fileType numberOfLoops:0];
}

- (void)playWithFileName:(NSString *)fileName
                fileType:(NSString *)fileType
           numberOfLoops:(NSInteger)numberOfLoops {
    [self playWithFileName:fileName fileType:fileType volume:-1 numberOfLoops:numberOfLoops];
}

- (void)playWithFileName:(NSString *)fileName
                fileType:(NSString *)fileType
                  volume:(float)volume
           numberOfLoops:(NSInteger)numberOfLoops{
    if (fileName && fileType) {
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:fileType];
        if (path) {
            NSURL *playUrl = [NSURL fileURLWithPath:path];
            if (playUrl) {
                NSError *error = nil;
                WXPKAudioPlayer *player = [[WXPKAudioPlayer alloc] initWithContentsOfURL:playUrl error:&error];
                if (volume > 0) {
                    player.volume = volume;
                }
                player.identifier = fileName;
                player.numberOfLoops = numberOfLoops > 0 ? numberOfLoops : 0;
                player.delegate = self;
                [player prepareToPlay];
                [player play];
                if (player) {
                    [self.playerDictM setSafeObject:player forSafeKey:player.identifier];
                }
            }else {
                NSLog(@"playUrl ===== nil");
            }
        }else {
            NSLog(@"path ====== nil");
        }
    }
}

#pragma mark - AVAudioPlayerDelegate
// 播放结束
- (void)audioPlayerDidFinishPlaying:(WXPKAudioPlayer *)player successfully:(BOOL)flag {
    [self stopWithPlayer:player];
}

#pragma mark - 中断监听回调
- (void)applicationWillResignActive:(NSNotification *)note {
    [self pauseAll];
}

- (void)applicationDidBecomeActive:(NSNotification *)note {
    [self playAll];
}

- (void)handleInterruption:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) { // 中断
        [self pauseAll];
    }else if (type == AVAudioSessionInterruptionTypeEnded) { // 中断结束
        [self playAll];
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            
        }
    }
}

#pragma mark - 线路发生改变回调
- (void)handleRouteChange:(NSNotification *)notification {
    NSDictionary *info = notification.userInfo;
    AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
    if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {  //旧音频设备断开
        //获取上一线路描述信息
        AVAudioSessionRouteDescription *previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];
        //获取上一线路的输出设备类型
        AVAudioSessionPortDescription *previousOutput = [previousRoute.outputs objectAtIndexSafe:0];
        NSString *portType = previousOutput.portType;
        if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
//            [self pauseAll];
        }
    }
}

#pragma mark - 暂停播放
- (void)pauseAll {
    for (id obj in self.playerDictM.allValues) {
        if ([obj isKindOfClass:[WXPKAudioPlayer class]]) {
            [(WXPKAudioPlayer *)obj pause];
        }
    }
}

#pragma mark - 开始播放
- (void)playAll {
    for (id obj in self.playerDictM.allValues) {
        if ([obj isKindOfClass:[WXPKAudioPlayer class]]) {
            [(WXPKAudioPlayer *)obj play];
        }
    }
}

#pragma mark - 停止播放
- (void)stopAll {
    for (id obj in self.playerDictM.allValues) {
        if ([obj isKindOfClass:[WXPKAudioPlayer class]]) {
            [(WXPKAudioPlayer *)obj stop];
        }
    }
    [self.playerDictM removeAllObjects];
}

- (void)stopWithFileName:(NSString *)fileName {
    id obj = [self.playerDictM objectForKey:fileName];
    if (obj && [obj isKindOfClass:[WXPKAudioPlayer class]]) {
        [(WXPKAudioPlayer *)obj stop];
        [self.playerDictM removeObjectForKey:fileName];
    }
}
- (void)stopWithPlayer:(WXPKAudioPlayer *)player {
    [player stop];
    [self.playerDictM removeObjectForKey:player.identifier];
    NSLog(@"stop_pk_audioName = %@, playerDictM = %@",player.identifier,self.playerDictM);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self stopAll];
}


@end
